//
//  MainMenuViewController.m
//  FreeSWITCH_Console
//
//  Created by Christopher Danielson on 4/6/09.
//  Copyright 2009 MaxPowerSoft, LLC. All rights reserved.
//

#import "MainMenuViewController.h"
#import "SwitchViewController.h"

@implementation MainMenuViewController

@synthesize list;
@synthesize tblView;

#pragma mark SQL Data Persistence
- (NSString *) dataFilePath {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
		
	return [documentsDirectory stringByAppendingPathComponent:kFileName];
}

- (void) createWriteableDB
{
    // See if writeable database already exists
    NSFileManager *fileManager = [NSFileManager defaultManager];
	NSString *writableDBPath = [self dataFilePath]; //[[documentsDirectory stringByAppendingPathComponent:kFileName] retain];
    // First time install
    if(![fileManager fileExistsAtPath:writableDBPath])
    {
	    NSString *readOnlyDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:kFileName];
        if(![fileManager copyItemAtPath:readOnlyDBPath toPath:writableDBPath error:nil])
        {
			NSAssert(0, @"Error creating table");
        }
    }
}

//load list data from persistent source
- (void) loadPersistentList {
	if (self.list != nil) [self.list release];
	
	[self createWriteableDB];
	
	if (sqlite3_open([[self dataFilePath] UTF8String], &database) != SQLITE_OK) {
		sqlite3_close(database);
		NSAssert(0, @"Failed to open database");
	}
	
	/*
	 CREATE TABLE FS_DATA (ROW INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, HOST TEXT, PORT INTEGER, PASSWORD TEXT);
	NSString *createSQL = @"CREATE TABLE IF NOT EXISTS FS_DATA (ROW INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, HOST TEXT, PORT INTEGER, PASSWORD TEXT);";
	if (sqlite3_exec (database, [createSQL  UTF8String], NULL, NULL, &errorMsg) != SQLITE_OK) {
		sqlite3_close(database);
		NSAssert1(0, @"Error creating table: %s", errorMsg);
	}
	*/

	UserSetting *us = [[UserSetting alloc] initWithName:@"Create New Connection" host:@"" port:8021 password:@""];
	NSMutableArray *array = [[NSMutableArray alloc] init];
	[array addObject:us];
	
	NSString *query = @"SELECT ROW, NAME, HOST, PORT, PASSWORD FROM FS_DATA ORDER BY ROW";
	sqlite3_stmt *statement;
	if (sqlite3_prepare_v2( database, [query UTF8String], -1, &statement, nil) == SQLITE_OK) {
		while (sqlite3_step(statement) == SQLITE_ROW) {
					
			int row = sqlite3_column_int(statement, 0);
			char *name = (char *)sqlite3_column_text(statement, 1);
			char *host = (char *)sqlite3_column_text(statement, 2);
			int port = sqlite3_column_int(statement, 3);
			char *pass = (char *)sqlite3_column_text(statement, 4);
			
			NSString *rowName = [[NSString alloc] initWithUTF8String:name];
			NSString *rowHost = [[NSString alloc] initWithUTF8String:host];
			NSString *rowPassword = [[NSString alloc] initWithUTF8String:pass];
			
			us = [[UserSetting alloc] initWithName:rowName host:rowHost port:port password:rowPassword];
			us.number = row;
			
			[rowName release];
			[rowHost release];
			[rowPassword release];
			
			[array addObject:us];

		}
		sqlite3_finalize(statement);
	}
	sqlite3_close(database);
	self.list = array;
}

- (void) addObjectToPersistentData:(UserSetting *)usrSet {
	if (usrSet.number < 1) {
		if (sqlite3_open([[self dataFilePath] UTF8String], &database) != SQLITE_OK) {
			sqlite3_close(database);
			NSAssert(0, @"Failed to open database");
		}

		if ([usrSet.name length] > 0)
			usrSet.name = [usrSet.name stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
		
		NSLog(@"[Before: %@]", usrSet.host);
		if ([usrSet.host length] > 0)
			usrSet.host = [usrSet.host stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
		NSLog(@"[After: %@]", usrSet.host);
		if ([usrSet.password length] > 0)
			usrSet.password = [usrSet.password stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
		
		NSLog(@"[Port: %d]", usrSet.port);
		
		const char *sql = "INSERT INTO FS_DATA (NAME, HOST, PORT, PASSWORD) VALUES (?,?,?,?);";		
		sqlite3_stmt *statement;
		
		if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) != SQLITE_OK) {
			NSAssert1(0, @"Error: failed to prepare create statement with message %s.", sqlite3_errmsg(database));
		}
		sqlite3_bind_text(statement, 1, [usrSet.name UTF8String], -1, SQLITE_TRANSIENT);
		sqlite3_bind_text(statement, 2, [usrSet.host UTF8String], -1, SQLITE_TRANSIENT);
		sqlite3_bind_int(statement, 3, usrSet.port);
		sqlite3_bind_text(statement, 4, [usrSet.password UTF8String], -1, SQLITE_TRANSIENT);
		if(sqlite3_step(statement) != SQLITE_DONE) {
			NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
        }
		
		sqlite3_finalize(statement);
		
		sqlite3_close(database);
		
		[self loadPersistentList];
		[tblView reloadData];
	}
}

#pragma mark UIViewController 
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	self.title = @"FreeSWITCH Menu";

	[self loadPersistentList];
	
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

- (void)dealloc {
	if (self.list != nil) [list release];
	[tblView release];
	[svc release];
    [super dealloc];
}

#pragma mark TableView Info

-(IBAction) toggleDeleteSelector {
	[self toggleEdit:nil];
}

-(IBAction) toggleEdit:(id)sender {
	if (self.tblView.editing) {
		UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithTitle:@"Delete" style:UIBarStyleDefault target:self action:@selector(toggleDeleteSelector)];
		UINavigationItem *navigationItem = [[UINavigationItem alloc] initWithTitle:@"FreeSWITCH Console"];
		navigationItem.rightBarButtonItem = buttonItem;
		[self.svc.mainMenuNavigationBar popNavigationItemAnimated:NO];
		[self.svc.mainMenuNavigationBar pushNavigationItem:navigationItem animated:NO];
		[navigationItem release];
		[buttonItem release];
		
	} else {
		UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarStyleDefault target:self action:@selector(toggleDeleteSelector)];
		UINavigationItem *navigationItem = [[UINavigationItem alloc] initWithTitle:@"FreeSWITCH Console"];
		navigationItem.rightBarButtonItem = buttonItem;
		[self.svc.mainMenuNavigationBar popNavigationItemAnimated:NO];
		[self.svc.mainMenuNavigationBar pushNavigationItem:navigationItem animated:NO];
		[navigationItem release];
		[buttonItem release];
	}
	[self.tblView setEditing:!self.tblView.editing animated:YES];	
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [self.list count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *UserSettingButtonCellIdentifier = @"UserSetting";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:UserSettingButtonCellIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier: UserSettingButtonCellIdentifier] autorelease];
	}
	NSUInteger row = [indexPath row];
	UserSetting *rowData = [list objectAtIndex:row];
	UIImage *image = [UIImage imageNamed:@"bullet_ball_glass_blue.png"];
	if (row != 0)
		cell.imageView.image = image;
	
	cell.textLabel.text = rowData.name;
	
#ifdef __IPHONE_3_0
	cell.accessoryType =  UITableViewCellAccessoryDisclosureIndicator;
#endif
	
	[rowData release];
	return cell;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
	NSUInteger row = [indexPath row];
	if (row == 0) 
		return UITableViewCellEditingStyleNone;
	else
		return UITableViewCellEditingStyleDelete;
}

#ifndef __IPHONE_3_0
- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
	return UITableViewCellAccessoryDisclosureIndicator;
}
#endif

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	NSUInteger row = [indexPath row];
	if (row == 0) {
		[self.switchViewController settingsView];
	} else {
		UserSetting *us = [list objectAtIndex:row];
		[self.switchViewController setUserSetting:us];
		[self.switchViewController consoleView];
	}
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
	
	NSUInteger row = [indexPath row];
	UserSetting *us = [list objectAtIndex:row];
	
	if (us != nil && us.number > 0) {
		if (sqlite3_open([[self dataFilePath] UTF8String], &database) != SQLITE_OK) {
			sqlite3_close(database);
			NSAssert(0, @"Failed to open database");
		}
		NSString *sql = [[NSString alloc] initWithFormat:@"DELETE FROM FS_DATA WHERE ROW=%d;", us.number];
		char * errorMsg;
		if (sqlite3_exec(database, [sql UTF8String], NULL, NULL, &errorMsg) != SQLITE_OK)
		{
			NSAssert1(0, @"Error deleting rowId. Error: %s", errorMsg);	
		}
		sqlite3_close(database);
	}
	
	[self.list removeObjectAtIndex:row];
	[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}


@end
